import { ColorUtil, getThemeColor } from 'pub-bbx-utils'
import { hexToHsb, hsbToHex, adjustBrightness } from '@src/util/color';

const ColorUtilInstance = new ColorUtil();

/**
 * @description 设置背景颜色到本地
 * @param {string} navColor 背景颜色
 */
const setNavBgToStorage = (navColor: string) => {
  localStorage.setItem('shb-theme-nav-color', navColor);
}

/**
 * @description 获取本地背景颜色，如果没有返回默认导航背景颜色
 * @returns {string} 背景颜色
 */
const getNavBgToStorage = () => {
  return localStorage.getItem('shb-theme-nav-color') || '#2F4858';
}

/**
 * @description 生成导航栏层次颜色
 * @param color 需要生成的颜色值
 * @returns {string[]} 生成的颜色数组
 */
const setNavLevelColor = (color: string) => {
  const navBgList = [] // 存储生成的数据数组
  let hsb = hexToHsb(color);
  const light = -10 // 减少亮度的变量
  for (let i = 0; i < 2; i++) {
    hsb = adjustBrightness(hsb, light * (i + 1))
    navBgList.push(hsbToHex(...hsb))
  }

  return navBgList
}

/**
 * @description 更新导航栏背景颜色
 * @param backgroundColor 
 */
const updateNavigationBackgroundColors = (backgroundColor: string) => {
  const navBgLevel = setNavLevelColor(backgroundColor);
  ColorUtilInstance.setNavBgColor(backgroundColor);
  document.documentElement.style.setProperty('--frame-nav-bg-color-level-2', navBgLevel[0]);
  document.documentElement.style.setProperty('--frame-nav-bg-color-level-3', navBgLevel[1]);
};

/**
 * @description 清除主题颜色、导航色
 */
const clearThemeColor = () => {
  localStorage.removeItem('shb-theme-color')
  localStorage.removeItem('shb-theme-nav-color')
}

export {
  ColorUtil,
  ColorUtilInstance,
  getThemeColor,
  setNavBgToStorage,
  getNavBgToStorage,
  setNavLevelColor,
  updateNavigationBackgroundColors,
  clearThemeColor
}
